<template>
  <view class="campus-container">
    <!-- 顶部导航栏 -->
    <view class="top-navbar">
      <!-- 搜索框 -->
      <view class="search-box" @click="gotoSearch">
        <text class="search-icon">🔍</text>
        <input type="text" class="search-input" placeholder="搜索" disabled />
      </view>
      <scroll-view scroll-x="true" class="navbar-scroll" show-scrollbar="false">
        <view
          class="navbar-item"
          v-for="(item, index) in categoryList"
          :key="index"
          :class="{ active: currentCategory === index }"
          @click="switchCategory(index)"
        >
          <text>{{ item.category_name }}</text>
          <view class="active-line" v-if="currentCategory === index"></view>
        </view>
      </scroll-view>
    </view>

    <!-- 瀑布流内容区 -->
    <scroll-view
      scroll-y="true"
      class="content-scroll"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
    >
      <view class="waterfall-container">
        <view
          class="campus-card"
          v-for="(item, index) in filteredData"
          :key="index"
          @click="viewDetail(item)"
        >
          <image
            class="card-image"
            :src="getFirstImage(item.article_images)"
            mode="widthFix"
          ></image>
          <view class="card-content">
            <view class="card-title">{{ item.article_title }}</view>
            <view class="card-footer">
              <view class="user-info">
                <image class="user-avatar" :src="item.user_avatar"></image>
                <text class="user-name">{{ item.user_nickname }}</text>
              </view>
              <view class="interaction">
                <text class="icon-heart">♡</text>
                <text class="like-count">{{ item.article_likes }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="isLoading">
        <text>加载中...</text>
      </view>
    </scroll-view>

    <tab-bar></tab-bar>
  </view>
</template>

<script setup>
  import { ref, computed, onMounted } from "vue";
  import { getCategory, getArticleList, like } from "../../api/campus";

  const categoryList = ref([]);
  // 当前选中的分类
  const currentCategory = ref(0);

  const campusData = ref([]);

  // 加载状态
  const isLoading = ref(false);
  // 是否还有更多数据
  const hasMore = ref(true);
  // 当前页码
  const currentPage = ref(1);
  // 下拉刷新状态
  const isRefreshing = ref(false);

  //获取分类列表
  const getCategoryList = async () => {
    const res = await getCategory();
    console.log(res);
    categoryList.value = res.data;
  };

  //获取文章列表
  const getArticleListData = async () => {
    const res = await getArticleList({
      page: currentPage.value,
      limit: 10,
    });
    campusData.value = res.data.data;
    console.log(res.data.data);
  };

  // 根据当前分类筛选数据
  const filteredData = computed(() => {
    const category = categoryList.value[currentCategory.value];
    if (!category || category.category_id === 1) {
      // 推荐分类的ID为1
      return campusData.value;
    } else {
      return campusData.value.filter(
        (item) => item.category_id === category.category_id
      );
    }
  });

  // 切换分类
  const switchCategory = async (index) => {
    currentCategory.value = index;
    // 切换分类后重置页码并刷新数据
    currentPage.value = 1;
    hasMore.value = true;

    // 获取选中分类的数据
    const category = categoryList.value[index];
    try {
      const res = await getArticleList({
        page: currentPage.value,
        limit: 10,
        category_id: category.category_id,
      });

      if (res.code === 200) {
        campusData.value = res.data.data;
      }
    } catch (error) {
      uni.showToast({
        title: "获取数据失败",
        icon: "error",
      });
    }
  };

  // 获取文章第一张图片
  const getFirstImage = (imageStr) => {
    try {
      if (typeof imageStr === "string") {
        const imageArray = JSON.parse(imageStr);
        if (Array.isArray(imageArray) && imageArray.length > 0) {
          return imageArray[0];
        }
      }
      return "../../static/img/default.jpg"; // 默认图片
    } catch (error) {
      console.error("解析图片失败:", error);
      return "../../static/img/default.jpg"; // 解析失败时返回默认图片
    }
  };

  // 查看详情
  const viewDetail = (item) => {
    // 跳转到详情页面，传递文章ID
    uni.navigateTo({
      url: `/pages/campus/detail?article_id=${item.article_id}`,
    });
  };

  // 下拉刷新
  const onRefresh = async () => {
    try {
      isRefreshing.value = true;
      currentPage.value = 1;
      hasMore.value = true;

      const res = await getArticleList({
        page: currentPage.value,
        limit: 10,
      });

      if (res.code === 200) {
        campusData.value = res.data.data;
      }
    } catch (error) {
      uni.showToast({
        title: "刷新失败",
        icon: "error",
      });
    } finally {
      isRefreshing.value = false;
    }
  };

  // 加载更多
  const loadMore = async () => {
    if (!hasMore.value || isLoading.value) return;

    isLoading.value = true;
    console.log("触发loadMore，当前页码：", currentPage.value);
    try {
      const category = categoryList.value[currentCategory.value];
      const params = {
        page: currentPage.value + 1,
        limit: 10,
      };

      // 如果不是推荐分类，添加分类ID
      if (category && category.category_id !== 1) {
        params.category_id = category.category_id;
      }

      console.log("加载更多请求参数：", params);
      const res = await getArticleList(params);

      if (res.code === 200 && res.data.data.length > 0) {
        currentPage.value++;
        campusData.value = [...campusData.value, ...res.data.data];
        hasMore.value = res.data.data.length === 10;
        console.log("加载更多成功，当前数据长度：", campusData.value.length);
      } else {
        hasMore.value = false;
        uni.showToast({
          title: "没有更多数据了",
          icon: "none",
        });
      }
    } catch (error) {
      uni.showToast({
        title: "加载失败",
        icon: "error",
      });
    } finally {
      isLoading.value = false;
    }
  };
  // 跳转到搜索页面
  const gotoSearch = () => {
    uni.navigateTo({
      url: "/pages/search/search",
    });
  };
  onMounted(() => {
    getArticleListData();
    getCategoryList();
  });
</script>

<style lang="scss">
  .campus-container {
    width: 750rpx;
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #f8f8f8;

    // 顶部导航栏样式
    .top-navbar {
      width: 100%;
      height: 200rpx;
      background-color: #fff;
      z-index: 100;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
      position: sticky;
      top: 0;
      transition: all 0.3s ease;
      &.shadow {
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.12);
      }
    }
    // 搜索框样式
    .search-box {
      width: 20%;
      height: 80rpx;
      background-color: #f5f5f5;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      padding: 0 30rpx;
      margin: 40rpx 20rpx 0 20rpx;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
      }

      .search-icon {
        font-size: 36rpx;
        color: #666;
        margin-right: 15rpx;
      }

      .search-input {
        flex: 1;
        height: 100%;
        font-size: 30rpx;
        color: #333;
        &::placeholder {
          color: #999;
        }
      }
    }

    .navbar-scroll {
      width: 100%;
      height: 90rpx;
      white-space: nowrap;
      padding: 0 20rpx;

      .navbar-item {
        display: inline-block;
        height: 90rpx;
        line-height: 90rpx;
        padding: 0 35rpx;
        font-size: 30rpx;
        position: relative;
        color: #666;
        transition: all 0.3s ease;

        &.active {
          color: #00879e;
          font-weight: 600;
          transform: scale(1.05);

          .active-line {
            position: absolute;
            bottom: 5rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 6rpx;
            background-color: #00879e;
            border-radius: 3rpx;
            transition: all 0.3s ease;
          }
        }
      }
    }
  }

  // 内容区域样式
  .content-scroll {
    flex: 1;
    width: 100%;
    height: calc(100vh - 200rpx);
    background-color: #f8f8f8;

    .waterfall-container {
      column-count: 2;
      column-gap: 20rpx;
      padding: 20rpx;
      box-sizing: border-box;
    }

    .campus-card {
      break-inside: avoid;
      margin-bottom: 20rpx;
      background-color: #fff;
      border-radius: 20rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      display: inline-block;
      width: 100%;
    }

    .card-image {
      width: 100%;
      height: auto;
      display: block;
      border-top-left-radius: 20rpx;
      border-top-right-radius: 20rpx;
    }

    .card-content {
      padding: 20rpx;
      flex: 1;
      display: flex;
      flex-direction: column;

      .card-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 10rpx;
      }

      .card-desc {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
        margin-bottom: 20rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }

      .card-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .user-info {
          display: flex;
          align-items: center;

          .user-avatar {
            width: 40rpx;
            height: 40rpx;
            border-radius: 50%;
            margin-right: 10rpx;
          }

          .user-name {
            font-size: 24rpx;
            color: #666;
          }
        }

        .interaction {
          display: flex;
          align-items: center;
          .like-count {
            font-size: 24rpx;
            color: #666;
            margin-right: 6rpx;
          }

          .icon-heart {
            font-size: 42rpx;
            margin-right: 10rpx;
          }
        }
      }
    }
  }

  // 加载更多提示
  .loading-more {
    text-align: center;
    padding: 20rpx 0;
    color: #999;
    font-size: 26rpx;
  }
</style>
